#
#   auth.py
#   journalismManger
#
#   Created by luoxh on 2019-07-24-17:35.
#   Copyright © 2019 luoxh. All rights reserved.
#
from functools import wraps

from flask import current_app, redirect, session, url_for
from mongoengine import DoesNotExist

from src.extension.exceptions import CustomException
from src.extension.status import CustomStatus
from src.model.admin import Admin


def _session_id(): return current_app.config.get('SESSION_AUTH_ID', 'auth')


def login_required(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        if _session_id() not in session: raise CustomException(CustomStatus.SESSION_ID_NOT_EXIST)
        return f(*args, **kwargs)

    return decorator


def not_login(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        if _session_id() in session: return redirect(url_for('admin.index'))
        return f(*args, **kwargs)

    return decorator


def current_user():
    try: admin = Admin.objects.get(username=session[_session_id()])
    except KeyError: raise CustomException(CustomStatus.SESSION_AUTH_NOT_EXIST)
    except DoesNotExist: raise CustomException(CustomStatus.USERNAME_DOES_NOT_EXIST)
    else: return admin


def set_session_msg(data, name=None):
    if isinstance(name, str): raise TypeError('The data for the meeting must be a string.')
    if name is not None: session[name] = data
    else: session[_session_id()] = data


def get_session_msg(name):
    if isinstance(name, str): raise TypeError('The name of the meeting must be a string.')
    try: msg = session[name]
    except KeyError: raise CustomException(CustomStatus.SESSION_ID_NOT_EXIST)
    else: return msg


def del_session_msg(name): del session[name]
